﻿using System;
using System.Speech.Recognition;
using System.Timers;


namespace SpeechRecognitionApp
{
    class Program
    {
        static float median = 1;
        static int count = 1;
        static Boolean secondclap = false;
        static DateTime dt;
        static DateTime olddt = DateTime.Now;
        static System.Timers.Timer aTimer;
        static SpeechRecognitionEngine speechRecognizer;
        static SpeechRecognitionEngine clapDetector;
    
        static void Main(string[] args)
        {
            // Create an in-process speech recognizer for the en-US locale.

            speechRecognizer =
              new SpeechRecognitionEngine(
                new System.Globalization.CultureInfo("en-US"));
            

                speechRecognizer.LoadGrammar(new Grammar(new GrammarBuilder("Jeeves")));
                // Add a handler for the speech recognized event.
                speechRecognizer.SpeechRecognized +=
                  new EventHandler<SpeechRecognizedEventArgs>(recognizer_SpeechRecognized);

                // Configure input to the speech recognizer.
                speechRecognizer.SetInputToDefaultAudioDevice();

                // Start asynchronous, continuous speech recognition.
                //speechRecognizer.RecognizeAsync(RecognizeMode.Multiple);



             clapDetector =
              new SpeechRecognitionEngine(
                new System.Globalization.CultureInfo("en-US"));
            

                clapDetector.LoadGrammar(new Grammar(new GrammarBuilder("Jeeves")));

                clapDetector.AudioLevelUpdated +=
                    new EventHandler<AudioLevelUpdatedEventArgs>(recognizer_AudioLevelUpdated);

                // Configure input to the speech recognizer.
                clapDetector.SetInputToDefaultAudioDevice();

                // Start asynchronous, continuous speech recognition.
                clapDetector.RecognizeAsync(RecognizeMode.Multiple);
                // Keep the console window open.
                while (true)
                {
                    Console.ReadLine();
                }
            
           
        }

        // Handle the SpeechRecognized event.
        static void recognizer_SpeechRecognized(object sender, SpeechRecognizedEventArgs e)
        {
            Console.WriteLine(e.Result.Text + ": Yes, master?");
        }

        static void recognizer_AudioLevelUpdated(object sender, AudioLevelUpdatedEventArgs e)
        {
            if (e.AudioLevel >= 20 + median)
            {
                //Console.WriteLine("Clap" + e.AudioLevel.ToString());
                dt = DateTime.Now;
                long timeNow = (dt.Hour * 3600 + dt.Minute * 60 + dt.Second) * 1000 + dt.Millisecond;
                long timeOld = (olddt.Hour * 3600 + olddt.Minute * 60 + olddt.Second) * 1000 + olddt.Millisecond;
                long interval = timeNow - timeOld;
                if (300 < interval && interval < 1000 && !secondclap)
                {
                    secondclap = true;
                    Console.WriteLine("DOUBLE CLAP DETECTED. I'm listening...");
                    // Create a timer with a ten second interval.
                    aTimer = new System.Timers.Timer(10000);

                    // Hook up the Elapsed event for the timer.
                    aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);

                    // Set the Interval to 2 seconds (2000 milliseconds).
                    aTimer.Interval = 2000;
                    aTimer.Enabled = true;

                    // Enable speech detection
                    speechRecognizer.RecognizeAsync(RecognizeMode.Multiple);
                    // Start synchronous speech recognition.
                    //speechRecognizer.RecognizeAsync(RecognizeMode.Multiple);

                }
               
                olddt = dt;
            }
            median = Math.Max(((count * median) + e.AudioLevel)/(++count), 0.1f);
            
            //Console.WriteLine("Audiolevel Updated: " + median);
            if (count == 10)
            {
                count = 0;
            }
        }
        // Specify what you want to happen when the Elapsed event is 
        // raised.
        private static void OnTimedEvent(object source, ElapsedEventArgs e)
        {
            Console.WriteLine("I'm not listening anymore. Please do a double clap to activate me again");
            aTimer.Stop();
            secondclap = false;
            speechRecognizer.RecognizeAsyncStop();
        }
    }
}
